package com.jzo2o.orders.manager.hander;

import com.alibaba.fastjson.JSON;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class TradeStatusMsgHandler {
    @Resource
    private IOrdersCreateService ordersCreateService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(value = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void handleTradeStatusMsg(String msg){
        log.info("接收到支付结果消息：Queue({})->{}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);
        //获取消息列表
        List<TradeStatusMsg> list = JSON.parseArray(msg, TradeStatusMsg.class);
        //循环处理每个支付结果消息
        for (TradeStatusMsg tradeStatusMsg : list) {
            //只处理jzo2o.orders标识的，并且状态为已结算的消息
            if ("jzo2o.orders".equals(tradeStatusMsg.getProductAppId())
                    && TradingStateEnum.YJS.getCode().equals(tradeStatusMsg.getStatusCode())) {
                //处理支付成功的消息
                ordersCreateService.paySuccess(tradeStatusMsg);
            }
        }
    }
}